<template>
  <div>
    <h1>WebSocket 客户端</h1>
    <p>{{ status }}</p>
    <textarea v-model="receivedMessages" rows="10" cols="50" readonly />
    <button @click="connect">连接</button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      status: '未连接',
      receivedMessages: '',
      socket: null
    }
  },
  methods: {
    connect() {
      try {
        // 创建 WebSocket 实例
        this.socket = new WebSocket('wss://api.gateio.ws/ws/v4/')

        this.socket.onopen = () => {
          this.status = 'WebSocket 客户端已连接'
          // 构造要发送的数据
          const unixTimestampSeconds = Math.floor(Date.now() / 1000)
          const list = ['BTC_USDT', 'ETH_USDT', 'BNB_USDT']
          const keyValuePairs = {
            time: 100,
            channel: 'spot.trades',
            event: 'subscribe',
            payload: list
          }
          const jsons = JSON.stringify(keyValuePairs)
          // 发送数据
          this.socket.send(jsons)
        }

        this.socket.onmessage = (event) => {
          // 处理接收到的消息
          this.receivedMessages += event.data + '\n'
        }

        this.socket.onclose = () => {
          this.status = 'WebSocket 连接已关闭'
        }

        this.socket.onerror = (error) => {
          this.status = `WebSocket 发生错误: ${error.message}`
        }
      } catch (error) {
        this.status = `连接失败: ${error.message}`
      }
    }
  }
}
</script>

  <style scoped>
  h1 {
    color: #333;
  }

  p {
    color: #666;
  }

  textarea {
    margin-top: 10px;
  }

  button {
    margin-top: 10px;
  }
  </style>
